//跨域 ajax方法
function postJson(url,info,callback,cross) {
    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(info),
        dataType: "json",
        contentType: 'text/plain',
        // crossDomain: cross || false,
        xhrFields: {
            withCredentials: cross || false
        },
        success: function (data) {
            callback(data);
        },
        error: function (data) {
            if(window.isDebug){
                console.log(data);
            }
        }
    });
}

//阻止冒泡事件
function stopEvent(event) {
    //取消事件冒泡
    var e = arguments.callee.caller.arguments[0] || event; //若省略此句，下面的e改为event，IE运行可以，但是其他浏览器就不兼容
    if (e && e.stopPropagation) {
        // this code is for Mozilla and Opera
        e.stopPropagation();
    } else if (window.event) {
        // this code is for IE
        window.event.cancelBubble = true;
    }
}

function getJson (url, info, callback) {
    $.ajax({
        type: "GET",
        url: url,
        data: info,
        dataType: "json",
        contentType: 'text/plain',
        success: function (data) {
            callback(data);
        },
        error: function (data) {
            if (window.isDebug) {
                console.log(data);
            }
        }
    });
}

// 瀑布流item链接跳转
$('.leftWrap').on("click", '.content-item', function(){
    var url = $(this).attr('data-detailUrl');
    if(url){
        window.open(url);
    }
});

// 个人中心item链接跳转
$('.mineListBox,.downListBox').on("click", 'li', function(){
    var url = $(this).attr('data-detailUrl');
    if(url){
        window.open(url);
    }
});

// 商城item链接跳转
$('.hotSell').on("click", '.hotItem', function(){
    var url = $(this).attr('data-detailUrl');
    if(url){
        window.open(url);
    }
});

$('.newProducts,.salesBox').on("click", 'li', function(){
    var url = $(this).attr('data-detailUrl');
    if(url){
        window.open(url);
    }
});

//遮罩跳转item链接
function toItemUrl(url){
    if(url){
        window.open(url);
    }
}

// 产品中心/相关文章item链接跳转
$('.productItem,.articlesItem').on("click", 'li', function(){
    var url = $(this).attr('data-productUrl') || $(this).attr('data-articlesUrl');
    if(url){
        window.open(url);
    }
});

//跳转会场阻止冒泡
function doAttend(){
    stopEvent('click');
}

//相关文章标签阻止冒泡
$('.toTag, .btn-buy-interested, .stop-propagation').on("click", function(){
    stopEvent('click');
});

$('.stopPropagation').on("click", function(){
    stopEvent('click');
});
//阻止标签点击冒泡
function stopRurnLik(){
    $(".blockTag").on('click', function() {
        stopEvent('click');
    });
}

//作者阻止冒泡
$('.leftWrap,.productItem').on("click", '.blockFrom', function(){
    stopEvent('click');
});



//评论阻止冒泡
// $('.leftWrap,.productItem').on("click", '.comment', function(){
//     stopEvent('click');
// });

//联系戴尔
$('.productItem,.leftWrap,.mineListBox').on("click", '.toSales', function(){
    stopEvent('click');
    var productId = $(this).parents('.content-item,li').attr('data-product-id'),
        productName = $(this).parents('.content-item,li').attr('data-product-name'),
        productPrice = $(this).parents('.content-item,li').attr('data-product-price'),
        entrance = productName+'/'+productId;
    // gio('track', 'ibuyClick', {'ibuyEntrancePageTitle': document.title, 'ibuyEntrancePageURL': document.URL})  //埋点实施方案
    window.open("https://www.dellemc-solution.com/personcenter/Sales.html?linksourcemodule="+$("#modifypassword").attr('data-module')+"&productid="+productId+"&productname="+productName+'&productprice='+productPrice+'&entrance='+entrance+"&backUrl="+ encodeURIComponent(window.location.href));
});

//点赞事件 参数：id=>文章id, status=>当前文章的点赞状态
$('.leftWrap,.productItem,.dialog-video-box,.dialog-filepre-box,.mineListBox,.g-detail-container').on("click", '.like', function(){
    stopEvent('click');
    var thisDom = $(this),
        id = thisDom.attr('data-id'),
        status = thisDom.attr('data-status'),
        title = thisDom.attr('data-title');

    var usrInfo = isLogin();
    //判断是否登陆
    if(!usrInfo){
        //行为记录
        if(status === 'true'){
            userRecode({behaviorType: '取消收藏', behaviorResult: '无',});
        }else{
            userRecode({behaviorType: '收藏', behaviorResult: '无',});
        }
        // window.location.href = window.cateData.url.loginAndBack;
        window.location.href = "https://www.dellemc-solution.com/personcenter/login.html?backUrl="+ encodeURIComponent(window.location.href);
        return;
    }

    //如果点赞状态为true 则取消点赞
    if(status === 'true'){
        //点赞-1
        postJson(window.cateData.api.like, {articleId:id, status:0, sess:usrInfo.session},function(data){
            if(data.result > 0){
                // loginOut(status);
                console.log(data.desc);
                return;
            }else{
                //记录我喜爱的内容点赞
                if(window.cateData.pageSubModule == 'favorite'){
                    $.cookie('cancelCollect',true);
                }

                $('.act-like-'+ id).find('.likeNum').text(data.total);
                $('.act-like-'+ id).find( '.like-icon').removeClass('status-like-true');
                $('.act-like-'+ id).find( '.like-icon').addClass('status-like-false');
                $('.act-like-'+ id).attr('data-status', 'false');
                //行为记录
                userRecode({behaviorType: '取消收藏', behaviorResult: title});
                msg.toast('点赞/收藏已取消');
                if(window.cateData.pageModule == 'detail'){
                    $(".sidebarWraArticle .zan").find("span").removeClass("coll");
                    $(".sidebarWraArticle .zan").attr("data-status",0);
                }
                if (window.cateData.pageModule == 'shopDetail') {
                    $('.j-collect-count').text(data.total);
                    thisDom.attr('data-status', 'false');
                    thisDom.find('.icon-appreciate-1').removeClass('u-orange');
                }
            }
        }, true);
    }else{
        //点赞+1
        postJson(window.cateData.api.like, {articleId:id, status:1, sess:usrInfo.session},function(data){
            if(data.result > 0){
                // loginOut(status);
                console.log(data.desc);
                return;
            }else{
                $('.act-like-'+ id).find('.likeNum').text(data.total);
                $('.act-like-'+ id).find( '.like-icon').addClass('status-like-true');
                $('.act-like-'+ id).find( '.like-icon').removeClass('status-like-false');
                $('.act-like-'+ id).attr('data-status', 'true');
                //行为记录
                userRecode({behaviorType: '收藏', behaviorResult: title});
                msg.toast('点赞并收藏成功');
                if(window.cateData.pageModule == 'detail'){
                    $(".sidebarWraArticle .zan").find("span").addClass("coll");
                    $(".sidebarWraArticle .zan").attr("data-status",1);
                }
                if (window.cateData.pageModule == 'shopDetail') {
                    $('.j-collect-count').text(data.total);
                    thisDom.attr('data-status', 'true');
                    thisDom.find('.icon-appreciate-1').addClass('u-orange');
                }
            }
        }, true);
    }
});

//sess 不对需要登出
function loginOut(status) {
    delCookie('smarketMember_' + window.cateData.schemaId);

    // gio('clearUserId');
    //行为记录
    if(status === 'true'){
        userRecode({behaviorType: '取消收藏', behaviorResult: '无',});
    }else{
        userRecode({behaviorType: '收藏', behaviorResult: '无',});
    }
    // window.location.href = window.cateData.url.loginAndBack;
    window.location.href = "https://www.dellemc-solution.com/personcenter/login.html?backUrl="+ encodeURIComponent(window.location.href);
}

//是否登陆
function isLogin() {
    var memberCookie = getCookie('smarketMember_' + window.cateData.schemaId);
    if (memberCookie) {
        return $.parseJSON(memberCookie);
    } else {
        // gio('clearUserId');
        return false;
    }
}

//退出登录
function logout () {
    // gio('clearUserId');
    userRecode({behaviorType: '退出登录', behaviorResult: '成功'});
    delCookie('smarketMember_' + window.cateData.schemaId);
    window.location.href = window.urlConfig.type + window.urlConfig.baseUrl + '?backUrl=' + window.urlConfig.backUrl;
}

//获取cookie
function getCookie(name) {
    var arr;
    var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        return decodeURIComponent(arr[2]);
    } else {
        return null;
    }
}

//写cookie
function setCookie(name, value, days) {
    var Days = days || 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + encodeURIComponent(value) + ";expires=" + exp.toGMTString() + ';domain=.dellemc-solution.com;path=/';
}

//删除cookie
function delCookie(key) {
    setCookie(key,'');
}

//处理时间
function handleTime() {
    $('.handle-time-box').each(function(){
        //获取页面的时间戳
        var timestamp = parseInt($(this).attr('date-timestamp'));
        if(!timestamp){
            return;
        }
        //处理时间
        var nowTime = parseInt(new Date().getTime() / 1000);
        var t = nowTime - timestamp;
        var res = '';

        //报名中t<0会是负数直接取接口时间
        if(t > 0){
            if(t < 3600){
                res = parseInt(t/60 )+ "分钟前";
            }else if (t>=3600 && t < 86400){
                res = parseInt(t/3600 )+ "小时前";
            }else if (t>=86400 && t < 864000){
                res = parseInt(t/86400 )+ "天前";
            }else{
                res = transformPHPTime(timestamp);
            }
            //设置时间
            $(this).text(res);
        }
    });

    //时间戳转日期
    function transformPHPTime(time){
        var date = new Date(time * 1000);

        var Y = date.getFullYear() + '-';
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        // var D = date.getDate() + ' ';
        var D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
        /*var h = date.getHours() + ':';
        var m = date.getMinutes() + ':';
        var s = date.getSeconds();*/

        return Y+M+D;
    }

}

//异步请求收藏数量，收藏状态，和评论数
function gettatInfo() {
    var handelArrEle = document.querySelectorAll('.handle-like-box');
    var articleIdArr = [];//要处理的文章id
    var elemArr = [];//需要处理的dom
    if(handelArrEle.length === 0){
        return;
    }

    $('.handle-like-box').each(function(){
        var articleId = $(this).attr('data-articleid');
        articleIdArr.push(articleId);
        elemArr[articleId] = $(this);
    });

    var articleIdStr = articleIdArr.join(',');

    var option = {
        'uid': window.cateData.userInfo.memberId,
        'articleId':articleIdStr
    };
    var postUrl = window.cateData.api.getCollectionStatus;
    postJson(postUrl, option, function (data) {
        if(data.result > 0){
            return;
        }
        $.each(data.content,function(index,value){
            $('.handle-like-box').each(function(){
                var articleId = $(this).attr('data-articleid');
                if(articleId === value.id) {
                    var likeStateWra = $(this).find('.like');  //点赞状态data-status
                    var likeStateEle = $(this).find('.like-icon');  //点赞状态点亮样式
                    var likeNumEle = $(this).find('.likeNum');  //点赞数
                    var commentNumEle = $(this).find('.commentNum');  //评论数
                    var browseNumEle = $(this).find('.browseNum');  //浏览量
                    if (likeStateEle) {
                        // console.log(value.id);
                        if (value.collect) {
                            // console.log(value.id+'点赞');
                            $(likeStateEle).removeClass('status-like-false');
                            $(likeStateEle).addClass('status-like-true');
                            $(likeStateWra).attr('data-status', true);
                        } else {
                            $(likeStateEle).removeClass('status-like-true');
                            $(likeStateEle).addClass('status-like-false');
                            $(likeStateWra).attr('data-status', false);
                        }
                    }
                    if (likeNumEle) {
                        likeNumEle.text(value.collectCount);
                    }
                    if (commentNumEle) {
                        commentNumEle.text(value.commentCount);
                    }
                    if (browseNumEle) {
                        browseNumEle.text(value.browseCount);
                    }
                }
            });
        });
    }, true);
}

//意向单埋码方法
function fireTag(){
    var evp = document.createElement('img');
    evp.height = 1;
    evp.width = 1;
    evp.style.display = "none";
    evp.src = "http://adfarm.mediaplex.com/ad/bk/10592-61498-3840-0?Enquiry_PopupClick_emc_sol=1&HVE_emc_sol=1&HVE=1&mpuid=" + document.location;
    document.body.appendChild(evp);
}

//单篇文章获取点赞状态
function getCollectionStatus(articleId, collectionEl) {

    collectionEl.className = 'like';

    collectionEl.classList.add('act-like-' + articleId);
    //设置id类
    var collectionIconEl = collectionEl.querySelector('.like-icon');

    var postUrl = window.cateData.api.getCollectionStatus;
    var option = {
        'uid': window.cateData.userInfo.memberId,
        'articleId': articleId
    };
    postJson(postUrl, option, function (data) {
        if (data.result > 0) {
            return;
        }
        if (data.content[0].collect) {
            collectionIconEl.classList.remove('status-like-false');
            collectionIconEl.classList.add('status-like-true');
            //设置状态
            collectionEl.setAttribute('data-status', 'true');
        } else {
            collectionIconEl.classList.remove('status-like-true');
            collectionIconEl.classList.add('status-like-false');
            //设置状态
            collectionEl.setAttribute('data-status', 'false');
        }
        return data.content;
    }, true);
}

//获取地址栏参数
function getUrlPara(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r !== null) {
        return decodeURIComponent(r[2]);
    }
    return null;
}

//弹窗后禁止后方页面滚动
var setScroll = {
    scrollTop: 0,
    isDisScroll: false,

    unScroll: function () {
        if (!this.isDisScroll) {
            this.scrollTop = $(window).scrollTop();
            document.body.classList.add('article-scroll-fixed');
            document.body.style.top = -this.scrollTop + 'px';
            this.isDisScroll = true;
        }
    },

    removeUnScroll: function() {
        document.body.classList.remove('article-scroll-fixed');
        $(window).scrollTop(this.scrollTop);
        this.isDisScroll = false;
    },
};

//关注 取消关注
var subscribe = function (authorId, authorName, status) {

    var bt = document.querySelector('.focusbt');
    var unbt = document.querySelector('.un-focusbt');
    //dom操作
    function setSubscribeBt() {
        unbt.classList.remove('hide');
        bt.classList.add('hide');
    }

    function setUnsubscribeBt() {
        bt.classList.remove('hide');
        unbt.classList.add('hide');
    }

    function loginStatus() {
        var usrInfo = isLogin();
        if (!usrInfo) {
            //行为记录
            if (status) {
                userRecode({behaviorType: '关注', behaviorResult: '无',});
            } else {
                userRecode({behaviorType: '取消关注', behaviorResult: '无',});
            }
            window.location.href = window.cateData.url.loginAndBack;
            return;
        }
    }

    var subscribeObj = {};
    var url = '';
    subscribeObj.do = function () {
        loginStatus();
        if(status){
            url = '/api/interaction/author/' + authorId + '/collect/' + 1;
            getJson(url, '',  function (data) {
                if(data.result == 0){
                    userRecode({behaviorType: '关注', behaviorResult: authorName});
                    setSubscribeBt();
                }else{
                    msg.toast(data.desc);
                }
            }, true);
        }else{
            url = '/api/interaction/author/' + authorId + '/collect/' + 0;
            getJson(url, '',  function (data) {
                if(data.result == 0){
                    userRecode({behaviorType: '取消关注', behaviorResult: authorName});
                    setUnsubscribeBt();
                }else{
                    msg.toast(data.desc);
                }
            }, true);
        }
    };
    return subscribeObj;
};

function numInput(inputCls, increaseCls, decreaseCls) {
    var _this = this;
    _this.inputDom = null;
    _this.increaseDom = null;
    _this.decreaseDom = null;

    _this.inputDom = document.querySelector(inputCls);
    _this.increaseDom = document.querySelector(increaseCls);
    _this.decreaseDom = document.querySelector(decreaseCls);

    if(!_this.inputDom || !_this.increaseDom || !_this.decreaseDom){
        return;
    }

    _this.inputVal = _this.inputDom.value;

    _this.increaseNum = function () {
        _this.inputVal++;
        _this.inputDom.value = _this.inputVal;
    };

    _this.decreaseNum = function () {
        if (_this.inputVal <= 1) {
            _this.inputVal = 1;
        } else {
            _this.inputVal--;
        }
        _this.inputDom.value = _this.inputVal;
    };

    _this.changeNum = function() {
        var curVal = _this.inputVal;
        if (!(/^(\d+)$/g.test(_this.inputDom.value))) {
            _this.inputDom.value = !_this.inputDom.value ? 1 : parseInt(curVal);
        }
        _this.inputVal = _this.inputDom.value;
    };

    _this.increaseDom.addEventListener('click', _this.increaseNum);
    _this.decreaseDom.addEventListener('click', _this.decreaseNum);
    _this.inputDom.addEventListener('keyup', _this.changeNum);

    _this.getInputVal = function () {
        return _this.inputVal;
    };

    _this.setInputVal = function (val) {
        _this.inputVal = val;
    };

    _this.destroy = function() {
        _this.increaseDom.removeEventListener('click', _this.increaseNum);
        _this.decreaseDom.removeEventListener('click', _this.decreaseNum);
    };

    return {
        setInputVal: this.setInputVal,
        getInputVal: this.getInputVal,
        destroy: this.destroy
    };
}

//获取表单字段值
//attrValue 属性 data-value 的名字
//changeFunc 界面输入改变后回调此函数
function HandelValue(attrValue, attrVerValue, attrVerElValue, inputErrorClass, emptyText, errorText, vFunc, callback) {
    this.el = document.querySelector('*[data-value="' + attrValue + '"]');
    this.errorEl = document.querySelector('*[data-value="' + attrVerValue + '"]');
    this.errorBoxEl = document.querySelector('*[data-value="' + attrVerElValue + '"]');
    this.value = '';
    this.isVerif = true;
    this.set = function (newValue) {
        this.el.value = newValue;
        this.value = newValue;
    };
    this.get = function () {
        return this.value;
    };
    var _this = this;
    this.change = function () {
        _this.value = _this.el.value;
        if(!_this.value){
            isErrr(emptyText);
        }else if(typeof(vFunc) === 'function' && !vFunc(_this.value)){
            isErrr(errorText);
        }else{
            isRight();
        }
        if( typeof(callback) === 'function'){
            callback(_this.isVerif);
        }
    };
    //初始化
    this.init = function(){
        isRight();
    };
    this.init();

    function isErrr(text) {
        _this.errorEl.textContent = text;
        _this.isVerif = false;
        _this.errorBoxEl.style.display="";
        _this.el.classList.add(inputErrorClass);
    }

    function isRight() {
        _this.errorEl.textContent = '';
        _this.isVerif = true;
        _this.errorBoxEl.style.display="none";
        _this.el.classList.remove(inputErrorClass);
    }
    this.el.addEventListener('keyup', this.change);

}

//处理表单radio字段
function HandelRadio(name) {
    this.radioName  = name;
    this.radios = document.getElementsByName(this.radioName);
    this.value = 0;
    this.resultValueArr = []; //samrket表单提交要求radio的值是个数组

    //设置
    this.set = function (value) {
        this.value = value;
        for(var i=0;i<this.radios.length;i++){
            if(this.radios[i].value === this.value){
                this.radios[i].checked = true;
            }
        }
    };

    //获取
    this.get = function () {
        for(var i=0;i<this.radios.length;i++){
            if(this.radios[i].checked === true){
                this.value = this.radios[i].value;
            }
        }
        this.resultValueArr.push(this.value)
        return this.resultValueArr;
    };
}

var baseVerif = {
    isMobile: function (str) {
        if (str === null || str === "") {
            return false;
        }
        var result = str.match(/^((\(\d{2,3}\))|(\d{3}\-))?((1\d{10}))$/);
        if (result === null) {
            return false;
        }
        return true;
    },
    //检查EMAIL
    isEmail: function (str) {
        var reg = /^\S+@\S+$/;
        var flag = reg.test(str);
        return flag;
    },

    //检查邮编
    isZipCode: function (str) {
        var reg = /^[0-9]{6}$/;
        var flag = reg.test(str);
        return flag;
    },

    //检查数字
    isNum: function (str) {
        var reg = /^\d+$/;
        var flag = reg.test(str);
        return flag;
    },

    //座机
    isPhone: function (str) {
        var reg = /^[0-9-()（）#]{2,18}$/;
        var flag = reg.test(str);
        return flag;
    }
}

//客服方法
var kefuServer = {
    shouqian:1,
    shouhou:2,
    shouqianSever: function () {
        openService(this.shouqian);
        // gio('track', 'click_presalesConsult', {'consultEntrancePage': document.title, 'consultEntrancePageURL': document.URL});  //埋点实施方案
    },
    shouhouServer: function () {
        openService(this.shouhou);
        // gio('track', 'click_aftersalesService',{'consultEntrancePage': document.title, 'consultEntrancePageURL': document.URL});  //埋点实施方案
    },
};

//我有意向购买按钮弹窗
function planBuyAct(productInfo){
    stopEvent('click');
    fireTag();
    var opts = {
        productid:'',
        productname:'',
        productprice:'',
        salePrice:'',
        productImg:'',
        productDesc:'',
        entrance:'',
        productnum:1
    };
    $.extend(opts, productInfo);
    console.log(opts);

    opts.entrance = opts.productName+'/'+opts.productId;
    opts.unSalePrice = opts.productprice;
    opts.productprice = opts.salePrice || opts.productprice || '';


    //打开弹窗
    msg.bargainDialog(opts, window.cateData.purchaseForm);

    //埋点实施方案
    // gio('track', 'ibuyClick', {'ibuyEntrancePageTitle': document.title, 'ibuyEntrancePageURL': document.URL})

}

//继承方法
function baseExtend (destination, source) {
    if (!source) {
        return destination;
    }
    for (var property in source) {
        destination[property] = source[property];
    }
    return destination;
}

//下载文件
function downFiles(filesIds, email, filesName, emailConfig, callback){

    //参数
    var option = {
        articleId: '',
        fileList: filesIds, //这里请传数组
        email: email,
        forEmailTemp: false,
        emailSubject: window.cateData.email.emailSubject,
        senderEmail: window.cateData.email.senderEmail,
        senderName: window.cateData.email.senderName,
        sess: window.cateData.userInfo.sess,
        openId: getUserInfo.options.openId,
        referenceUrl: window.location.href,
        instanceId: 0,
        moduleType: 0,
        extra: {
            tenantId: window.cateData.tenantId,
            instanceId: 0,
            memberId: window.cateData.userInfo.memberId,
            moduleId: 0,
            openId: getUserInfo.options.openId,
            weChatId: window.cateData.weChatId,
            objInstanceId: 0,
            source: window.cateData.device,
        },
        globalUserId: getUserInfo.options.globalUserId,
        browseInfo: client.browseInfo,
    };

    var info = baseExtend(option, emailConfig);

    function sendFile() {
        postJson(window.cateData.api.downloadByEmail, info, function (data) {
            if (data.body.result !== 0) {
                msg.toast(data.body.desc);
                //用户行为
                userRecode({behaviorType: '下载资料', behaviorResult: '下载失败'});
            } else {
                //用户行为
                userRecode({behaviorType: '下载资料', behaviorResult: filesName||'未知文件'});
                callback(data.body);
                msg.toastSedfile();
            }
        });
    }
    sendFile();
}